#include "Sock.hpp"
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fstream>

#define WWWROOT "./wwwroot/"
#define HOME_PAGE "index.html"
#define SIZE 1024 * 10
void Usage(char *proc)
{
    cout << "Usage:" << proc << " port " << endl;
}

void *HttpResponceRoutine(void *args)
{
    int sock = *(int *)args;
    delete (int *)args;
    pthread_detach(pthread_self());
    char buffer[SIZE] = {0};
    // 读取请求信息
    ssize_t s = recv(sock, buffer, sizeof(buffer), 0);
    if (s > 0)
    {
        buffer[s] = 0;
        cout << buffer << endl;
        // 构建响应
        string html_file = WWWROOT;
        html_file += HOME_PAGE;
        struct stat st;
        stat(html_file.c_str(), &st);

        /* string responce;
        // responce += "HTTP/1.1 301 Permanently moved\n"; // 永久重定向
        responce += "HTTP/1.1 302 Found\n"; // 临时重定向
        responce += "Location: https://www.qq.com/\n";
        responce += "\n";
        send(sock, responce.c_str(), responce.size(), 0); */

        // 正文数据类型、属性
        string responce;
        responce += "HTTP/1.0 200 OK\n";
        responce += "Content-Type: text/html;charset=utf-8\n"; // 设置编码格式
        responce += "Content-Lenth: ";
        responce += to_string(st.st_size); // 文件内容大小
        responce += "\n";
        responce += "Set-Cookie: id=123456\n";
        responce += "Set-Cookie: password=xscandctforever\n";

        responce += "\n";

        // 正文
        ifstream in(html_file);
        if (!in.is_open())
        {
            cerr << "open html error!" << endl;
        }
        else
        {
            string line;
            while (getline(in, line))
            {
                responce += line;
            }
            // 发送响应至客户端
            send(sock, responce.c_str(), responce.size(), 0);
        }
    }

    close(sock);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
    }
    int listen_sock = Sock::Socket();
    uint16_t port = atoi(argv[1]);
    Sock::Bind(listen_sock, port);
    Sock::Listen(listen_sock);
    // 提供服务
    while (true)
    {
        int newsock = Sock::Accept(listen_sock);
        if (newsock < 0)
        {
            cerr << "Accept error!" << endl;
            return 1;
        }
        pthread_t tid;
        int *sock = new int(newsock);
        pthread_create(&tid, nullptr, HttpResponceRoutine, (void *)sock);
    }
    return 0;
}